<?php

class Model_Product extends Model {

    function __construct() {
        $this->Lookup = getModel('Model_Lookup');
        $this->Product_application = getModel('Model_ProductApplication');
        $this->ProductReports = getModel('Model_ProductReports');
        $this->ProductReportsComment = getModel('Model_ProductReportsComment');
        $this->MemberLike = getModel('Model_MemberLike');
        $this->ModelMember = getModel('Model_Member');
        $this->email_obj = getLibClass('itrialEmail');
        $this->Points = getModel('Model_Points');
        $this->ProductNew = getModel('Model_ProductNew');
    }

    /* 獲得列表資料
     * $member_type		int		1試用會員 5體驗團 0全部
     * $type			int		0全部時間	1使用邀請時間範圍內	2提交報告時間範圍內 3已錯過邀請時間
     * $orderby		string	 	字段名 desc 或 字段名 asc
     * $page		int			當前頁數
     * $size		int			獲取個數
     * return		array		資料數組
     */

    function h_get_product_list($h_param = array()) {
        $prama = array();
        $prama_key_0 = array('keyword', 'category', 'index', 'scores', 'category_id', 'brand', 'is_mobile', 'pid');
        if ($prama_key_0) {
            foreach ($prama_key_0 as $value) {
                $prama[$value] = (!empty($h_param[$value])) ? $h_param[$value] : 0;
            }
        }
        $prama_key_1 = array('member_type', 'type', 'page');
        if ($prama_key_1) {
            foreach ($prama_key_1 as $value) {
                $prama[$value] = (!empty($h_param[$value]) || $h_param[$value] == "0") ? $h_param[$value] : 1;
            }
        }

        $prama['orderby'] = (!empty($h_param['orderby'])) ? $h_param['orderby'] : "TB1.id desc";
        $prama['size'] = (!empty($h_param['size'])) ? $h_param['size'] : 3;
        $prama['keyword'] = (!empty($h_param['keyword'])) ? $h_param['keyword'] : "";

        return $this->getProductList($prama['member_type'], $prama['type'], $prama['orderby'], $prama['page'], $prama['size'], $prama['keyword'], $prama['category'], $prama['index'], $prama['scores'], $prama['category_id'], $prama['brand'], $prama['is_mobile'], $prama['pid']);
    }

    /* 獲得列表資料
     * $member_type		int		1試用會員 5體驗團 0全部
     * $type			int		0全部時間	1使用邀請時間範圍內	2提交報告時間範圍內 3已錯過邀請時間 4開始申請時間後的 5提交報告時間後的 6開始提交報告後，並且報告數大於1的 7、comming
     * $orderby		string	 	字段名 desc 或 字段名 asc
     * $page		int			當前頁數
     * $size		int			獲取個數
     * return		array		資料數組
     */

    function getProductList($member_type = 1, $type = 1, $orderby = "TB1.id desc", $page = 1, $size = 3, $keyword = '', $category = 0, $index = 0, $scores = 0, $category_id = 0, $brand = 0, $is_mobile = 0, $pid = 0) {

        $orderby = $orderby;

        $param = array();
        // change by hong -> where is_trial
        $param['where'] = $is_mobile ? " 1 " : "TB1.status=1 and TB1.is_live=1";
        //if(intval($category)) $param['where'] .= " and TB1.product_type=".intval($category);
        $param['field'] = "TB1.id,TB1.min_pic_num,TB1.max_pic_num,TB1.trial_terms,TB1.tag,TB1.points,TB1.vote_option,TB1.about_txt,	TB1.attribute_label1,	TB1.attribute_value1,	TB1.attribute_label2,	TB1.attribute_value2,	TB1.attribute_label3,	TB1.attribute_value3,	TB1.attribute_label4,	TB1.attribute_value4,	TB1.attribute_label5,	TB1.attribute_value5,	TB1.attribute_label6,	TB1.attribute_value6,	TB1.attribute_label7,	TB1.attribute_value7,	TB1.attribute_label8,	TB1.attribute_value8,	TB1.questions_json,TB1.is_live,TB1.is_trial,TB1.status,TB1.apply_endtime,TB1.apply_starttime,TB1.report_starttime,TB1.report_endtime,TB1.reports,TB1.name,TB1.cname,TB1.brand,TB1.quota,(TB1.apply_num + TB1.apply_num_offset) as apply_num ,(TB1.click + TB1.click_offset) as click,(TB1.likes + TB1.likes_offset) as likes,TB1.body,TB1.about_url,TB1.cover_image1 as cover,TB1.is_hightlight,TB1.member_type,TB1.price,TB1.capacity_trial,TB1.product_layout_category,TB1.lastmodify,(TB2.scores+TB2.scores_base) AS scores,TB2.well, TB2.category_score_num, TB2.category_score1, TB2.category_score2, TB2.category_score3, TB2.category_score4, TB2.category_score5, TB2.category_score6, TB2.category_score7, TB2.category_score8, TB2.well_score_num1, TB2.well_score_num2, TB2.well_score_num3, TB2.well_score_num4, TB2.well_score_num5, TB2.agegroup1, TB2.agegroup2, TB2.agegroup3, TB2.agegroup4, TB2.agegroup5, TB2.agegroup6";
        switch ($member_type) {
            case 1:

                $param['where'] .= " and TB1.member_type=1";
                break;
            case 5:

                $param['where'] .= " and TB1.member_type=5";
                break;
            case 0:

                $param['where'] .= "";
                break;

            default:
                return false;
                break;
        }
        switch ($type) {
            case 1:
                $param['where'] .= " and TB1.is_trial=1 and '" . date('Y-m-d H:i:s', time()) . "' between TB1.apply_starttime and TB1.apply_endtime ";
                break;
            case 2:
                $param['where'] .= " and TB1.is_trial=1 and '" . date('Y-m-d H:i:s', time()) . "' between TB1.report_starttime and TB1.report_endtime ";
                break;
            case 3:
                $param['where'] .= " and TB1.is_trial=1 and '" . date('Y-m-d H:i:s', time()) . "' >= TB1.apply_endtime ";
                break;
            case 4:
                $param['where'] .= " and TB1.is_trial=1 and '" . date('Y-m-d H:i:s', time()) . "' >= TB1.apply_starttime ";
                break;
            case 5:
                $param['where'] .= " and TB1.is_trial=1 and '" . date('Y-m-d H:i:s', time()) . "' >= TB1.report_starttime ";
                break;
            case 6:
                $param['where'] .= " and TB1.is_trial=1 and '" . date('Y-m-d H:i:s', time()) . "' >= TB1.report_starttime and TB1.reports>0";
                break;
            case 7:
                $param['where'] .= " and TB1.is_trial=1 and '" . date('Y-m-d H:i:s', time()) . "' < TB1.apply_starttime ";
                break;
            case 0:
                $param['where'] .= "";
                break;

            default:
                return false;
                break;
        }

        if ($scores)
            $param['where'] .= " and TB2.scores>0";

        if (intval($pid) > 0) {
            $param['where'] .= " and TB1.id=" . intval($pid);
        }

        /*
          if($index) {

          $paramc = array();
          $paramc['field'] = "product";
          $paramc['where'] = "status=1";
          $paramc['order'] = "sequence asc,id desc"; //"id asc"
          $paramc['group'] = "";
          $paramc['limit'] = 8;
          $paramc['pagesize'] = "";
          $paramc['page'] = "";
          $paramc['join'] = "";
          $paramc['on'] = "";
          $dataindex = db_query_hash('hilite_trial_product',$paramc);
          $orderby = "";

          $indexids = "";
          if($dataindex['result']){
          foreach ($dataindex['result'] as $value) {
          $indexids.=$indexids?",".$value['product']:$value['product'];
          }
          if($indexids)  $param['where'] .="  and TB1.id in (".$indexids.")";
          }

          }
         */
        if ($keyword) {

            $keyword = addcheck($keyword);
            $paramb = array();
            $paramb['field'] = "id";
            $paramb['where'] = "status=1 and name like '%" . $keyword . "%'";
            $paramb['order'] = "id asc"; //"id asc"
            $paramb['group'] = "";
            $paramb['limit'] = "";
            $paramb['pagesize'] = "";
            $paramb['page'] = "";
            $paramb['join'] = "";
            $paramb['on'] = "";
            $databrand = db_query_hash('brand', $paramb);


            $orbrand = "";
            $brandids = "";
            if ($databrand['result']) {
                foreach ($databrand['result'] as $value) {
                    $brandids.=$brandids ? "," . $value['id'] : $value['id'];
                }
                if ($brandids)
                    $orbrand = "or TB1.brand in (" . $brandids . ")";
            }

            $param['where'] .=" and (TB1.name like '%" . $keyword . "%' or TB1.tag like '%" . $keyword . "%'  or TB1.cname like '%" . $keyword . "%' $orbrand )";
        }

        if (intval($category)) {
            $where = "status=1 and topid = " . intval($category);

            $param1 = array();
            $param1['field'] = "id,name,cname";
            $param1['where'] = $where;
            $param1['order'] = "id asc"; //"id asc"
            $param1['group'] = "";
            $param1['limit'] = "";
            $param1['pagesize'] = "";
            $param1['page'] = "";
            $param1['join'] = "";
            $param1['on'] = "";
            $data = db_query_hash('product_layout_category', $param1);
            $result = array();
            if ($data['result']) {
                foreach ($data['result'] as $key => $value) {
                    $result[] = $value['id'];
                }
            }
            $ids = implode(',', $result);
            $param['where'] .=" and TB1.product_layout_category in (" . $ids . ")";
        }

        if (intval($category_id)) {
            $where = "status=1 and id = " . intval($category_id);

            $param1 = array();
            $param1['field'] = "id,name,cname";
            $param1['where'] = $where;
            $param1['order'] = "id asc"; //"id asc"
            $param1['group'] = "";
            $param1['limit'] = "";
            $param1['pagesize'] = "";
            $param1['page'] = "";
            $param1['join'] = "";
            $param1['on'] = "";
            $data = db_query_one('product_layout_category', $param1);
            $ids = !empty($data['result']['id']) ? $data['result']['id'] : 0;
            $param['where'] .=" and TB1.product_layout_category =" . $ids;
        }

        if (intval($brand)) {
            $param['where'] .=" and TB1.brand =" . $brand;
        }


        $param['order'] = $orderby; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = $size;
        $param['page'] = $page;
        $param['join'] = "LEFT JOIN product_reports_stat";
        $param['on'] = "TB1.id = TB2.oid";

        //$data = db_query_hash('product',$param,"","read",1);

        $data = db_query_hash('product', $param);




        $product_layout_category = $this->Lookup->getLookup('product_layout_category_all');

        $topidarr = array();
        if ($product_layout_category['result']) {
            foreach ($product_layout_category['result'] as $value) {
                $topidarr[$value['id']] = $value['topid'];
            }
        }

        $categoryArr = array();
        if ($product_layout_category['result']) {
            foreach ($product_layout_category['result'] as $value) {
                $categoryArr[$value['id']] = $value['cname'];
            }
        }

        $brandarr = array();
        $brand = $this->Lookup->getLookup('brand');
        if ($brand['result']) {
            foreach ($brand['result'] as $value) {
                $brandarr[$value['id']] = $value['name'];
            }
        }
        /*
          $product_layout_categoryarr = array();
          $product_layout_category = $this->Lookup->getLookup('product_layout_category');
          if($product_layout_category['result']){
          foreach ($product_layout_category['result'] as $value) {
          $product_layout_categoryarr[$value['id']]=$value['name'];
          }
          }
         */



        $result = array();
        if ($data['result']) {
            foreach ($data['result'] as $key => $value) {
                if ($value['scores'] > 100)
                    $value['scores'] = 100;

                $categoryName = "";
                if (array_key_exists($value['product_layout_category'], $topidarr)) {
                    if (array_key_exists($topidarr[$value['product_layout_category']], $categoryArr))
                        $categoryName = $categoryArr[$topidarr[$value['product_layout_category']]];
                }
                $value['type_name'] = @$brandarr[$value['brand']];

                $value['categoryName'] = $categoryName;
                $value['category'] = @$topidarr[$value['product_layout_category']];
                if (!$value['cname'])
                    $value['cname'] = $value['name'];
                $result[$key] = $value;
            }
        }


        /*
          $result = array();
          if($data['result']){
          foreach ($data['result'] as $key => $value) {

          $value['type_name'] = @$brandarr[$value['brand']];

          $value['categoryName'] = @$product_layout_categoryarr[$value['product_type']];

          $value['category'] = $value['product_type'];

          $result[$key]=$value;
          }
          }
         */
        /*
          if($index){
          $result = array();
          if($data['result']){
          foreach ($data['result'] as $key => $value) {
          $result[$value['id']]=$value;
          }
          }

          $indexarr = array();
          $indexResult = array();
          $indexarr = explode(",",$indexids);

          foreach ($indexarr as  $value) {
          if(@!$result[$value]) continue;
          $indexResult[$value]=$result[$value];
          }

          $result = $indexResult;
          }
         */


        $data['result'] = $result;

        return $data;
    }

    /* 獲得產品詳情資料
     * $id 			int			產品ID
     * return		array		資料數組
     */

    function getProductById($id = 0, $status = 1) {
        if (!intval($id))
            return false;
        $param = array();
        $param['field'] = "id,points,apply_endtime,reports,name,cname,brand,product_type,quota,(apply_num + apply_num_offset) as apply_num ,(click + click_offset) as click,(likes + likes_offset) as likes,body,about_url,cover_image1 as cover,is_hightlight,member_type,apply_starttime,report_starttime,report_endtime,price_trial,capacity_trial,product_layout_category,vote_option,tag,about_txt,price,n_attrubute,	attribute_label1,	attribute_value1,	attribute_label2,	attribute_value2,	attribute_label3,	attribute_value3,	attribute_label4,	attribute_value4,	attribute_label5,	attribute_value5,	attribute_label6,	attribute_value6,	attribute_label7,	attribute_value7,	attribute_label8,	attribute_value8,	questions_json,is_trial,is_live,status,trial_terms,min_pic_num,max_pic_num,lastmodify";
        $param['where'] = "is_live=1  and id=" . intval($id);
        if (intval($status) == 1) {
            $param['where'] .=" and status=1";
        }

        //$param['where'] = "status=1 and id=".intval($id);
        $param['order'] = ""; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $data = db_query_hash('product', $param);

        if (empty($data['result']))
            return array();

        $param = array();
        $param['field'] = "";
        $param['where'] = "id=" . $data['result'][0]['brand'];
        $param['order'] = ""; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $brand_data = db_query_hash('brand', $param);

        $param = array();
        $param['field'] = "id, oid, well, category_score_num, category_score1, category_score2, category_score3, category_score4, category_score5, category_score6, category_score7, category_score8, well_score_num1, well_score_num2, well_score_num3, well_score_num4, well_score_num5, agegroup1, agegroup2, agegroup3, agegroup4, agegroup5, agegroup6,(scores+scores_base) AS scores,scores_base";
        $param['where'] = "oid=" . intval($id);
        $param['order'] = ""; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $product_reports_status_data = db_query_hash('product_reports_stat', $param);
        $product_reports_status_data_array = array();
        $product_reports_status_data_array['good'] = 0;
        $product_reports_status_data_array['common'] = 0;
        $product_reports_status_data_array['bad'] = 0;

        if ($product_reports_status_data['result']) {
            $product_reports_status_data_array = $product_reports_status_data['result'][0];

            $product_reports_status_data_array['good'] = $product_reports_status_data_array['well_score_num1'] + $product_reports_status_data_array['well_score_num2'];
            $product_reports_status_data_array['common'] = $product_reports_status_data_array['well_score_num3'];
            $product_reports_status_data_array['bad'] = $product_reports_status_data_array['well_score_num4'] + $product_reports_status_data_array['well_score_num5'];
        }

        $result = array();
        if ($data['result']) {
            $param = array();
            $vote_option_data = array();
            if ($data['result'][0]['vote_option']) {
                $param['field'] = "id,cname";
                $param['where'] = "id in(" . $data['result'][0]['vote_option'] . ")";
                $param['order'] = "id asc"; //"id asc"
                $param['group'] = "";
                $param['limit'] = "";
                $param['pagesize'] = "";
                $param['page'] = "";
                $param['join'] = "";
                $param['on'] = "";
                $vote_option_data = db_query_hash('product_vote_option', $param);
            }

            $product_layout_category = $this->Lookup->getLookup('product_layout_category_all');

            $topidarr = array();
            if ($product_layout_category['result']) {
                foreach ($product_layout_category['result'] as $value) {
                    $topidarr[$value['id']] = $value['topid'];
                }
            }

            $categoryArr = array();
            if ($product_layout_category['result']) {
                foreach ($product_layout_category['result'] as $value) {
                    $categoryArr[$value['id']] = $value['cname'];
                }
            }


            foreach ($data['result'] as $key => $value) {
                
                $categoryName = "";
                if (array_key_exists($value['product_layout_category'], $topidarr)) {
                    if (array_key_exists($topidarr[$value['product_layout_category']], $categoryArr))
                        $categoryName = @$categoryArr[$topidarr[$value['product_layout_category']]];
                }

                $value['categoryName'] = $categoryName;
                $value['category'] = @$topidarr[$value['product_layout_category']];
                
                

                $value['type_name'] = $brand_data['result'][0]['name'];
                $value['type_cname'] = $brand_data['result'][0]['cname'];
                if (!$value['cname'])
                    $value['cname'] = $value['name'];

                if (isset($product_reports_status_data_array['scores']) && $product_reports_status_data_array['scores'] > 100)
                    $product_reports_status_data_array['scores'] = 100;
                $value['product_reports_stat'] = $product_reports_status_data_array;
                $value['vote_option_data'] = $vote_option_data;
                $result[$key] = $value;
            }
        }



        return $result[0];
    }

    /**
      function share_fb($mid, $pid, $body, $global_url) {
      $facebookarr = array();
      $facebook = $this->ModelMember->getMemberFacebook($mid);
      if ($facebook['result'])
      $facebookarr = $facebook['result'][0];
      if (!$facebookarr['accesstoken']) {
      $this->iframeReturn(null, 'callback', array('retcode' => 8, 'msg' => NO_LOGIN_FB));
      } else {

      require_once(LIB_PATH . '/Vendor/Facebook/sdk/facebook.php');
      require_once(LIB_PATH . '/Vendor/Facebook/FaceBookApi.class.php');

      $fb_config = array();
      $fb_config['appId'] = FB_APPID;
      $fb_config['secret'] = FB_SECRET;
      $fb_config['scope'] = FB_SCOPE;
      $fb_config['cookie'] = FB_COOKIE;
      $fb_config['fileUpload'] = FB_FILEUPLOAD_SUPPORT;

      $product = $this->get_product_byid($pid);

      $params = array(
      'name' => $product['cname'] . '申請試用',
      'link' => $global_url . "product.php?action=submit_application&pid=" . $pid,
      'description' => $body,
      'picture' => $global_url . PhotoResize($product['cover'], 158, 158),
      );

      $facebook = new FaceBookApi($fb_config);
      $facebook->postToWall($facebookarr['fb_id'], $facebookarr['accesstoken'], $params);
      }
      return TRUE;
      }
     * */
    function get_product_info($pid, $pub = 0) {
        $product = $this->get_product_byid($pid, $pub);
        if (!empty($product)) {
            if (!empty($product['price'])) {
                $product['_attr']['價格'] = '$' . $product['price'];
            }

            if (!empty($product['attribute_value1'])) {
                $product['_attr']['實際容量'] = $product['attribute_value1'];
            }
            if (!empty($product['capacity_trial'])) {
                $product['_attr']['體驗規格'] = $product['capacity_trial'];
            }
            if (!empty($product['body'])) {
                $product['_attr']['編輯短評'] = nl2br($product['body']);
            }
            if (!empty($product['tag'])) {

                $tags = explode("|", $product['tag']);
                $tags_str = "";
                foreach ($tags as $key => $value) {
                    $s = $key == 0 ? '' : ', ';
                    $tags_str .= $s . "<a class='tag_name' href='/search-product/" . trim($value) . "'>" . $value . "</a>";
                }
                $product['_attr']['標籤'] = $tags_str;
            }
            $product['_photo_url'] = PhotoResize($product['cover'], 158, 158);
            $product['_difTime'] = explode(" ", str_diff_time($product['apply_endtime']));
            $product['questions'] = json_decode($product['questions_json'], 1);
            //	if(!empty($product['attribute_value1'])){ $product['_attr']['實際容量'] = nl2br($product['attribute_value1']);}
            //	if(!empty($product['capacity_trial'])){ $product['_attr']['體驗規格'] = $product['capacity_trial'];}
            //	for($i=2;$i<9;$i++){	if(!empty($product['attribute_value'.$i])){ $product['_attr'][$product['attribute_label'.$i]] = nl2br($product['attribute_value'.$i]);}}
            //	if(!empty($product['about_url']) && !empty($product['about_txt'])){ $product['_attr']['相關資料'] = "<a target='_blank' href='".$product['about_url']."' target>".nl2br($product['about_txt'])."</a>";}
        }
        return $product;
    }

    function get_product_byid($pid, $pub = 0) {
        $product = array();
        if (empty($pub)) {
            $product = $this->getProductById($pid);
        } else {
            $product = $this->getProductById($pid, 2);
        }
        if (!$product) {
            return showMsgCode('產品id出錯或尚未開始試用！', '/');
        }

        $product['min_pic_num'] = !empty($product['min_pic_num']) ? $product['min_pic_num'] : ($product['member_type'] == 5 ? 5 : 3);
        $product['max_pic_num'] = !empty($product['max_pic_num']) ? $product['max_pic_num'] : ($product['member_type'] == 5 ? 10 : 6);
        return $product;
    }

    function submit_application_updb($array, $product, $global_url) {
        $attr = $mjson = array();
        $attr['oid'] = $array['pid'];
        $attr['mid'] = $array['mid'];
        $attr['application_status'] = 1;
        $attr['status'] = 1;
        $attr['body'] = $array['reason'];
        /**
          $reason_size = $array['reason_size'];
          if (empty($attr['body']) || intval($reason_size) > 100) {
          return array(null, 'callback', array('retcode' => 1, 'msg' => HAS_INVITE_REASON));
          }

          $mjson['itrial_url'] = htmlspecialchars($this->get_q('itrial_url',''));
          if(empty($mjson['itrial_url'])){
          return array(null,'callback',array('retcode'=>2,'msg'=>HAS_REPORT_URL));
          }

          $mjson['www_url2'] = htmlspecialchars($this->get_q('www_url2',''));
          if(empty($mjson['www_url2'])){
          return array(null,'callback',array('retcode'=>3,'msg'=>HAS_WWW_URL));
          }
         * */
        $mjson['photo'] = $array['photo'];
        if (empty($mjson['photo'])) {
            return array(null, 'callback', array('retcode' => 4, 'msg' => HAS_INVITE_PIC));
        }

        $ques = $array['ques'];

        if ($ques) {
            foreach ($ques as $k => $v) {
                if (empty($v['a'])) {
                    return array(array('k' => $k), 'callback', array('retcode' => 5, 'msg' => HAS_REPORT_QUESTION));
                }
                if (is_array($mjson['questions'][$k]['a'])) {
                    $mjson['questions'][$k]['a'] = implode(',', $v['a']);
                } else {
                    $mjson['questions'][$k] = htmlspecialchars($v['a']);
                }
            }
        }

        $isread = $array['isread'];
        if (empty($isread)) {
            return array(null, 'callback', array('retcode' => 7, 'msg' => HAS_AGREE_TERMS));
        }

        if ($array['facebook']) {
            //$global_url = $this->param('URL');
            //$this->share_fb($this->member['id'], $pid, $attr['body'],$global_url);
            $attr['is_fb_share'] = 1;
        }

        $attr['message_json'] = json_encode($mjson);
        $attr['addtime'] = date('Y-m-d H:i:s');

        $_name = !empty($product['cname']) ? $product['cname'] : $product['name'];
        $_mem1 = $this->ModelMember->getMember($array['mid']);
        if (intval($_mem1['result'][0]['points']) < intval($product['points'])) {
            return array(null, 'callback', array('retcode' => 9, 'msg' => '您的積分不足，無法申請產品 - ' . $_name));
        }
        $res = db_add('product_application', $attr);
        if ($res) {
            $this->Points->points_record($array['mid'], "submit_product_invite", str_replace("[產品名稱]", $_name, SUBMIT_PRODUCT_INVITE_LANG), $array['pid'], $product['points']);

            $_product_one = db_query_one('product', array('field' => 'apply_num', 'where' => 'id=' . $attr['oid']));
            $apply_num = intval($_product_one['result']['apply_num']) + 1;
            db_update('product', array('apply_num' => $apply_num, 'modifiedby' => 1, 'lastmodify' => date('Y-m-d H:i:s')), ' id=' . mysql_escape_string($attr['oid']));

            $emailUrl = $global_url . optimize_url('product', 'invite_inpage', 'mtype=' . $product['member_type'] . '&pid=' . $attr['oid']);

            $name = !empty($product['cname']) ? $product['cname'] : $product['name'];
            if ($product['member_type'] == 5) {
                $this->email_obj->send($array['mid'], "app_try_fa", array('cname' => $name, 'emailUrl' => $emailUrl));
            } else {

                $this->email_obj->send($array['mid'], "app_try_fb", array('cname' => $name, 'emailUrl' => $emailUrl));
            }

            return array(null, 'callback', array('retcode' => 10, 'msg' => 'success'));
        }
        return 1;
    }

    function get_detail_report_list($mid, $pid, $order, $page, $product, $global_url) {
        $orderby = $order == 2 ? "TB1.likes desc" : "TB1.priority desc,TB1.addtime desc";
        $reports_list = $this->ProductReports->getReportsList($pid, 0, 0, $orderby, $page, 5, 1);

        if (!empty($reports_list['result'])) {
            foreach ($reports_list['result'] as $k => $v) {
                $reports_list['result'][$k]['photo_l'] = imore_avatar($v['photo']);
                $reports_list['result'][$k]['body'] = wordscut($v['body'], 100);
                $reports_list['result'][$k]['comments'] = db_query_count('product_reports_comment', "oid=" . mysql_escape_string($v['id']) . " and status=1");
                $reports_list['result'][$k]['share_url'] = optimize_url('product', 'reportDetail', 'mtype=' . $product['member_type'] . '&pid=' . $pid . '&rid=' . $v['id']);

                $fb_result = file_get_contents("http://graph.facebook.com/" . $global_url . substr($reports_list['result'][$k]['share_url'], 1));
                $fb_array = json_decode($fb_result, 1);
                $reports_list['result'][$k]['fb_count'] = $fb_array['shares'] + $v['fb_share_num_base'];

                //用戶報告圖文
                if (!empty($v['content_json'])) {
                    $content_arr = json_decode($v['content_json'], true);
                    $ii = 1;
                    foreach ($content_arr as $v1) {
                        if (!empty($v1['p'])) {
                            $reports_list['_content'][$k][$ii]['p1'] = PhotoResize($v1['p'], 163, 102,0);
                            $ii++;
                        }
                    }
                }

                //用戶滿意度
                $j = 0;
                for ($i = 1; $i < 9; $i++) {
                    if (isset($product['vote_option_data']['result'][$i - 1]) && !empty($product['vote_option_data']['result'][$i - 1])) {
                        $reports_list['_category_score'][$k][$j]['k'] = $reports_list['result'][$k]['category_score' . $i];
                        $reports_list['_category_score'][$k][$j]['v'] = $product['vote_option_data']['result'][$i - 1]['cname'];
                        $j++;
                    }
                }

                //是否已關注該用戶
                if (!empty($mid)) {
                    $_islike = $this->MemberLike->getMemberLike($mid, 'member', $v['mid']);
                } else {
                    $_islike = 0;
                }
                $reports_list['result'][$k]['islike'] = !empty($_islike) ? 1 : 0;

                $user = $this->ModelMember->getMember($v['mid']);
                $reports_list['result'][$k]['user_type'] = $user['result'][0]['member_type'];
            }
        }

        return $reports_list;
    }

    function get_detail_report_one($mid, $pid, $rid, $product, $pview, $pv_arr = array()) {
        $agegroup_list = $this->Lookup->getLookup('agegroup');
        $body_skin_list = $this->Lookup->getLookup('body_skin'); //膚質
        $reports_list_res = array();
        if (empty($pview)) {
            $reports_list = $this->ProductReports->getReportsList($pid, 0, $rid, 'TB1.id desc', 1, 1, 1);

            if (!empty($reports_list['result'][0])) {
                $reports_list_res = $reports_list['result'][0];
            } else {
                return showMsgCode('記錄不存在或已經刪除！', '/');
            }
            if (!empty($reports_list_res)) {
                $reports_list_res['photo_l'] = imore_avatar($reports_list_res['photo']);
                //用戶報告圖文
                if (!empty($reports_list_res['content_json'])) {
                    $reports_list_res['_content'] = json_decode($reports_list_res['content_json'], true);
                }

                //用戶滿意度
                $j = 0;
                for ($i = 1; $i < 9; $i++) {
                    if (isset($product['vote_option_data']['result'][$i - 1]) && !empty($product['vote_option_data']['result'][$i - 1])) {
                        $reports_list_res['_category_score'][$j]['k'] = $reports_list_res['category_score' . $i];
                        $reports_list_res['_category_score'][$j]['v'] = $product['vote_option_data']['result'][$i - 1]['cname'];
                        $j++;
                    }
                }

                //是否已關注該用戶
                if (!empty($mid)) {
                    $_islike = $this->MemberLike->getMemberLike($mid, 'member', $reports_list_res['mid']);
                    $user = $this->ModelMember->getMember($reports_list_res['mid']);
                    $reports_list_res['user_type'] = $user['result'][0]['member_type'];
                } else {
                    $_islike = 0;
                }
                $reports_list_res['islike'] = !empty($_islike) ? 1 : 0;
                $reports_list_res['agegroup_cname'] = $agegroup_list['result'][intval($reports_list_res['agegroup']) - 1]['cname'];
                $reports_list_res['share_url'] = optimize_url('product', 'reportDetail', 'mtype=' . $product['member_type'] . '&pid=' . $pid . '&rid=' . $rid);
            }

            //上一頁、下一頁
            if (!empty($reports_list['previous'])) {
                $reports_list_res['previous'] = $reports_list['previous'];
            } else {
                $reports_list_res['previous']['id'] = 0;
                $reports_list_res['previous']['title'] = '沒有了';
            }
            if (!empty($reports_list['next'])) {
                $reports_list_res['next'] = $reports_list['next'];
            } else {
                $reports_list_res['next']['id'] = 0;
                $reports_list_res['next']['title'] = '沒有了';
            }
        } else {
            $reports_list_res = $pv_arr;
            $reports_list_res['agegroup_cname'] = $agegroup_list['result'][$pv_arr['agegroup'] - 1]['cname'];
            $reports_list_res['body_skin'] = $body_skin_list['result'][$pv_arr['body_skin_id'] - 1]['cname'];
        }
        return $reports_list_res;
    }

    function report_add_submit_updb($attr, $other, $product, $is_edit = 0, $rid = 0, $global_url = "") {
        $pic = $pic_c = array();
        $is_draft = !empty($other['is_draft']) ? $other['is_draft'] : 0; //是否草稿，草稿不用判斷
        //<!--字段判斷
        if (empty($is_draft)) {
            if (empty($attr['title'])) {
                return array(null, 'callback', array('retcode' => 1, 'msg' => HAS_REPORT_TITLE));
            }

            if ($other['pic']) {
                foreach ($other['pic'] as $k => $v) {
                    if (!empty($v['p'])) {
                        //if(empty($v['t']) || intval($v['s'])<50){
                        //	return array(array($k),'callback',array('retcode'=>3,'msg'=>HAS_MORE_TXT_50));
                        //}
                        if (!empty($v['t']))
                            $v['t'] = htmlspecialchars($v['t']);
                        $pic[$k] = $v;
                        if (in_array($other['pic_c'][$k], $pic_c)) {
                            return array(array($k), 'callback', array('retcode' => 3, 'msg' => ERR_SAME_PIC));
                        } else {
                            $pic_c[] = $other['pic_c'][$k];
                        }
                    }
                }
            }


            if (count($pic_c) < $product['min_pic_num']) {
                return array(null, 'callback', array('retcode' => 2, 'msg' => "請最少上傳" . $product['min_pic_num'] . "張圖片"));
            }

            if (empty($attr['body']) || intval($other['body_size']) < 150 || intval($other['body_size']) > 300) {
                return array(null, 'callback', array('retcode' => 4, 'msg' => HAS_MORE_TXT_100));
            }
        } else {
            if ($other['pic']) {
                foreach ($other['pic'] as $k => $v) {
                    //if (!empty($v['p'])) {
                    //if(empty($v['t']) || intval($v['s'])<50){
                    //	return array(array($k),'callback',array('retcode'=>3,'msg'=>HAS_MORE_TXT_50));
                    //}

                    if (!empty($v['t']))
                        $v['t'] = htmlspecialchars($v['t']);
                    $pic[$k] = $v;
                    $pic_c[] = $other['pic_c'][$k];
                    //}
                }
            }
        }
        // end 字段判斷-->

        $attr['status'] = 1;
        if ($is_edit == 0)
            $attr['addtime'] = date('Y-m-d H:i:s');
        $attr['content_json'] = json_encode($pic);

        if (empty($is_draft)) {//是否草稿狀態
            $attr['is_valid'] = 1;
            $attr['is_publish'] = 1;
            if (empty($is_edit)) {//是否編輯狀態
                $attr['is_accept'] = (!empty($other['mem_app']) && $other['mem_app']['is_submitted'] == 0) ? 0 : 1;
                $res2 = db_add('product_reports', $attr);
                if ($res2) {
                    if (!empty($other['mem_app'])) {
                        if (time() >= strtotime($other['mem_app']['report_starttime']) && time() <= (strtotime($other['mem_app']['report_endtime']) + 7 * 24 * 3600)) {
                            db_update('member_application', array('is_submitted' => 1, 'rid' => $res2), ' product=' . mysql_escape_string($attr['oid']) . ' and mid=' . mysql_escape_string($attr['mid']) . ' and status=1 and rid=0');
                        }
                    }
                    $_name = !empty($product['cname']) ? $product['cname'] : $product['name'];
                    if (!empty($other['mem_app']) && time() >= strtotime($other['mem_app']['report_endtime']) && time() <= (strtotime($other['mem_app']['report_endtime']) + 7 * 24 * 3600)) {
                        //sos('delay');
                        $this->Points->points_record($attr['mid'], "delay_report", str_replace("[產品名稱]", $_name, DELAY_REPORT_LANG));
                    }
//                    if (!empty($other['mem_app'])) {
//                        $this->Points->points_record($attr['mid'], "submit_report", "提交報告加分錄入");
//                        $user_sum = db_query_count('product_reports', 'oid=' . $attr['oid'] . ' and id in(select rid from member_application where product=' . $attr['oid'] . ') and is_publish=1 and status=1');
//                        if ($user_sum <= 3)
//                            $this->Points->points_record($attr['mid'], "become_report_3rd", "提交報告前三名加分錄入");
//                    } else {
//                        $this->Points->points_record($attr['mid'], "submit_topic", "提交心得加分錄入");
//                    }
                    if (empty($other['mem_app']) || $other['mem_app']['is_submitted'] == 1) {
                        $this->Points->points_record($attr['mid'], "submit_topic", str_replace("[產品名稱]", $_name, SUBMIT_TOPIC_LANG));
                        $getURL = $global_url . "product.php?action=approveReport&pid=" . $attr['oid'] . "&rid=" . $res2 . "&key=" . md5($attr['oid'] . $res2 . "imoreHK");
                        file_get_contents($getURL);
                    }


                    $emailUrl = $global_url . optimize_url('product', 'detail', 'mtype=' . $product['member_type'] . "&pid=" . $attr['oid']);
                    $this->email_obj->send($attr['mid'], "submit_report_success", array('cname' => $product['cname'], 'emailUrl' => $emailUrl, 'cdate' => $product['report_endtime']));
                    return array(array('id' => $res2), 'callback', array('retcode' => 5, 'msg' => 'success'));
                } else {
                    return array(null, 'callback', array('retcode' => 6, 'msg' => 'error'));
                }
            } else {
                $attr['lastmodify'] = date('Y-m-d H:i:s');
				$attr['reject_reason'] = 0;
                $mid = $attr['mid'];
                unset($attr['mid']);
                $res2 = db_update('product_reports', $attr, 'id=' . mysql_escape_string($rid));
                if ($res2) {
                    $getURL = $global_url . "product.php?action=approveReport&pid=" . $attr['oid'] . "&rid=" . $rid . "&key=" . md5($attr['oid'] . $rid . "imoreHK");
                    file_get_contents($getURL);
                    if (!empty($other['mem_app']) && time() >= strtotime($other['mem_app']['report_starttime']) && time() <= (strtotime($other['mem_app']['report_endtime']) + 7 * 24 * 3600)) {
                        db_update('member_application', array('is_submitted' => 1, 'rid' => $rid, 'addtime' => date('Y-m-d H:i:s')), ' product=' . mysql_escape_string($attr['oid']) . ' and mid=' . mysql_escape_string($mid) . ' and status=1 and rid=0');
                    }
                    return array(array('id' => $rid), 'callback', array('retcode' => 5, 'msg' => 'success'));
                } else {
                    return array(null, 'callback', array('retcode' => 6, 'msg' => 'error'));
                }
            }
        } else {
            $attr['is_publish'] = 0;
            $has_draft = db_query_count('product_reports', 'oid=' . mysql_escape_string($attr['oid']) . ' and mid=' . mysql_escape_string($attr['mid']) . ' and is_publish=0 and is_accept=0 and status=1');
            if (intval($has_draft) > 0) {
                $mid = $attr['mid'];
                unset($attr['mid']);
                db_update('product_reports', $attr, 'oid=' . mysql_escape_string($attr['oid']) . ' and mid=' . mysql_escape_string($mid) . ' and is_publish=0 and is_accept=0');
            } else {
                db_add('product_reports', $attr);
            }
            return array(null, 'callback', array('retcode' => 7, 'msg' => 'success'));
        }
        return 1;
    }

    function invite_data($mid, $pid, $page, $pub = 0) {
        $_p = (intval($pub) == 1) ? 1 : 0;
        $pagesize = 5;
        $product = $this->get_product_info($pid, $_p);

        $mtype = $product['member_type'];
        $tmpl = $mtype == 5 ? 'p_invite_inpage_expert.php' : 'p_invite_inpage_general.php';

        $product_user_list = $this->Product_application->getAllUser($pid, 2);
        $userlist = isset($product_user_list['result']) && !empty($product_user_list['result']) ? $product_user_list['result'] : array();
        if ($userlist) {
            foreach ($userlist as $k => $v) {
                $userlist[$k]['photo_l'] = imore_avatar($v['photo']);
            }
        }

        $product_app_list = $this->Product_application->getApplicationList($pid, 4, "id desc", $page, $pagesize);

        $reportlist = isset($product_app_list['result']) && !empty($product_app_list['result']) ? $product_app_list['result'] : array();
        if ($reportlist) {
            foreach ($reportlist as $k => $v) {
                $reportlist[$k]['photo_l'] = imore_avatar($v['photo']);
            }
        }

        $pagelist = '';
        if (!empty($product_app_list) && !empty($product_app_list['pageinfo']['total'])) {
            $pagelist = showPage($product_app_list['pageinfo']['total'], $pagesize, $page, optimize_url('product', 'invite_inpage', 'mtype=' . $mtype . '&pid=' . $pid));
        }

        //是否隱藏已申請會員及三部曲部份
        $turnpage = $page > 1 ? 1 : 0;
        $s = 0;
        if (!empty($mid)) {
            $_mem = $this->ModelMember->getMemberCondition($mid);
            $_member_arr = array();
            if ($_mem['result'])
                $_member_arr = $_mem['result'][0];
            if (!empty($_member_arr['address']) && !empty($_member_arr['homepage'])) {
                $s = 1;
            } else {
                $s = 0;
            }
        } else {
            $s = 0;
        }
        $pageValue = $pageoptions = array();
        $pageValue['title'] = !empty($product['type_name']) ? $product['type_name'] . " - " : "";
        $pageValue['title'] .=!empty($product['cname']) ? $product['cname'] . " - " : "";
        $pageoptions['csses'][0] = "jquery.lightbox-0.5";
        $pageoptions['jses'][0] = "jquery.lightbox-0.5.min";
        $retDatas = array(
            's' => $s,
            'mtype' => $mtype,
            'turnpage' => $turnpage,
            'pagelist' => $pagelist,
            'product' => $product,
            'userlist' => $userlist,
            'reportlist' => $reportlist,
            'pageValue' => $pageValue,
            'pageoptions' => $pageoptions,
            'tmpl' => $tmpl
        );

        return $retDatas;
    }

    function get_new_invite_list() {
        //$data1 = $this->Product->getProductList(0,1,"TB1.apply_endtime desc,TB1.id desc",1,7,"",0,1);
        $new_list = $this->ProductNew->getList();
        //echo '<pre>'.var_export($new_list,1).'</pre>'; exit;

        $invite_new_list = array();
        $ii = 0;
        if (!empty($new_list['result'])) {
            foreach ($new_list['result'] as $k => $v) {
                $invite_new_list[$ii] = $v;

                $invite_new_list[$ii]['_difTime'] = time() < strtotime($v['apply_starttime']) ? 0 : explode(" ", str_diff_time($v['apply_endtime']));

                //$_data = $this->Product->getProductById($v['id']);
                //$data1['result'][$k]['capacity'] = $_data['attribute_value1'];
                if ($k == 0) {
                    $invite_new_list[$ii]['name'] = wordscut($v['name'], 20);
                    $invite_new_list[$ii]['cname'] = wordscut($v['cname'], 20);
                } else {
                    $invite_new_list[$ii]['name'] = wordscut($v['name'], 11);
                    $invite_new_list[$ii]['cname'] = wordscut($v['cname'], 11);
                }
                if ($ii == 0) {
                    $invite_new_list[$ii]['_photo_url'] = PhotoResize($v['cover'], 322, 225);
                } else {
                    $invite_new_list[$ii]['_photo_url'] = PhotoResize($v['cover'], 158, 158);
                }
                $ii = $ii + 1;
            }
        }
        return $invite_new_list;
    }

    function get_submit_report_list() {
        $submit_report_list = $this->getProductList(0, 2, "TB1.report_starttime desc", 1, 4);
        if (!empty($submit_report_list['result'])) {
            foreach ($submit_report_list['result'] as $k => $v) {
                $submit_report_list['result'][$k]['name'] = wordscut($v['name'], 11);
                $submit_report_list['result'][$k]['cname'] = wordscut($v['cname'], 11);
                $submit_report_list['result'][$k]['_photo_url'] = PhotoResize($v['cover'], 111, 111);
                $submit_report_list['result'][$k]['_rep_count'] = db_query_count('product_reports', 'status=1 and oid=' . mysql_escape_string($v['id']));
            }
        }
        return $submit_report_list;
    }

    function get_new_report_list() {
        $reports = db_query_hash('member_application', array('field' => 'product,mid,rid', 'where' => 'is_submitted=1 and status=1', 'order' => 'addtime desc'));

        $new_report_list = $term = array();
        if (!empty($reports['result'])) {
            foreach (array(5, 1) as $v1) {
                $ii = 0;
                foreach ($reports['result'] as $k => $v) {
                    if ($v['product'] == 9966)
                        continue;

                    $product_info = $this->getProductById($v['product']);

                    if (!empty($product_info)) {
                        $all = @($product_info['product_reports_stat']['scores']) ? round($product_info['product_reports_stat']['scores']) : 0;
                        if (!in_array($v['product'], $term) && intval($all) > 0 && !empty($product_info['reports']) && $product_info['member_type'] == $v1) {
                            $new_report_list['result'][$k]['_photo_url'] = PhotoResize($product_info['cover'], 130, 130);
                            $new_report_list['result'][$k]['name'] = wordscut($product_info['name'], 10);
                            $new_report_list['result'][$k]['cname'] = wordscut($product_info['cname'], 10);
                            $new_report_list['result'][$k]['id'] = $product_info['id'];
                            $new_report_list['result'][$k]['member_type'] = $product_info['member_type'];
                            $new_report_list['result'][$k]['price'] = $product_info['price'];
                            $new_report_list['result'][$k]['type_name'] = $product_info['type_name'];
                            $new_report_list['result'][$k]['quota'] = $product_info['quota'];
                            $new_report_list['result'][$k]['apply_num'] = $product_info['apply_num'];
                            $new_report_list['result'][$k]['click'] = $product_info['click'];
                            //總評
                            $new_report_list['result'][$k]['_overall'] = $all;
                            $ii++;
                            $term[] = $v['product'];
                        }
                        if ($ii > 1) {
                            break;
                        }
                        /* $new_report_list['result'][$k]['_reports'] = $data4[$k]['reports'];
                          $new_report_list['result'][$k]['_real_volume'] = $data4[$k]['attribute_value1'];
                          $data5[$k] = $this->ProductReports->getReportsList($v['id'],0,0,"TB1.id desc",1, 6);

                          //報告總數
                          $new_report_list['result'][$k]['_rpsum'] = $data5[$k]['pageinfo']['total'];

                          foreach($data5[$k]['result'] as $k1=>$v1){
                          $data5[$k]['result'][$k1]['member_type'] = $data4[$k]['member_type'];
                          $data5[$k]['result'][$k1]['photo_l'] = PhotoResize($v1['photo'],50,50);
                          } */
                    }
                }
            }
        }
        return $new_report_list;
    }

}

?>